package com.isc.tcpFileUpload01;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 1.编写一个服务端和一个客户端
 * 2.服务器在8888端口监听
 * 3.客户端连接到服务器，发送一张图片 d:\\5t5.jpg
 * 4.服务器端接收到客户端发送的图片，保存到src下，发送"收到图片"再退出
 * 5.客户端接收到服务器端发送的"收到图片",再退出
 * 6.该程序要求使用StreamUtils.java
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //服务器在8888端口监听
        int port = 8888;
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("正在监听" + port + "端口...");
        //已连接套接字
        Socket accept = serverSocket.accept();
        System.out.println("与客户端已建立连接...");

        //服务器接收客户端发送的文件
        //1.暂存文件
        InputStream inputStream = accept.getInputStream();
        int readLength = 0;//读取长度
        byte[] buf = new byte[1024];//读取数据缓冲区
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((readLength = inputStream.read(buf)) != -1) {
            baos.write(buf, 0, readLength);//向baos流写入每次暂存的buf数据(追加方式)
        }
        //temp是文件暂存的字节数组
        byte[] temp = baos.toByteArray();
        System.out.println("文件暂存成功~");

        //2.保存文件到src下
        String destFilePath = "src\\5t5.jpg";
        FileOutputStream fos = new FileOutputStream(destFilePath);
        fos.write(temp);

        //关闭资源
        fos.close();
        baos.close();
        System.out.println("文件已保存到服务器~");

        //3.回复消息
        OutputStream outputStream = accept.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        bw.write("服务器已收到文件~");
        bw.newLine();
        bw.flush();

        //关闭资源
        bw.close();
        outputStream.close();
        inputStream.close();
        accept.close();
        serverSocket.close();
    }
}
